package logic

import (
	"context"
	"home-mgr/model"

	"home-mgr/homerpc/homerpc"
	"home-mgr/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HouseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseListLogic {
	return &HouseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseListLogic) HouseList(in *homerpc.HouseListRequest) (*homerpc.HouseListResponse, error) {
	// todo: add your logic here and delete this line

	var houses []model.HouseUser

	offset := (in.Page - 1) * in.Size

	tx := model.DB.Debug().
		Model(model.House{}).
		Select("houses.*, users.name as user_name").
		Joins("left join users on houses.user_id = users.id ").
		Offset(int(offset)).
		Limit(int(in.Size))

	if in.PriceOrder == 1 {
		tx = tx.Order("price asc")
	}
	if in.PriceOrder == 2 {
		tx = tx.Order("price desc")
	}
	if in.TimeOrder == 1 {
		tx = tx.Order("created_at asc")
	}
	if in.TimeOrder == 2 {
		tx = tx.Order("created_at desc")
	}
	tx.Find(&houses)

	var houselist []*homerpc.HouseList
	for _, house := range houses {

		list := homerpc.HouseList{
			UserId:  int64(house.UserId),
			Title:   house.Title,
			Content: house.Content,
			Price:   float32(house.Price),
			Address: house.Address,
		}
		houselist = append(houselist, &list)
	}
	return &homerpc.HouseListResponse{
		List: houselist,
	}, nil
}
